import React, { Component } from 'react';
import { Form, InputNumber, DatePicker, Select, Input, Button, Tooltip, Space, Row, Col, Cascader, Checkbox, TreeSelect } from 'antd'
import {
  SearchOutlined, SyncOutlined
} from '@ant-design/icons';
import './style.less'
import PropTypes from 'prop-types'
import _ from 'lodash'
import treeData from "@/utils/treeData.json";
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select

export default class TheQueryForm extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      layout: {
        labelCol: { span: 10 },
        wrapperCol: { span: 14 },
      },
      labelCol: 7,
      wrapperCol: 17,
      formOption: []
    }
  }

  componentDidMount() {
    const { labelCol } = this.props
    if (labelCol && labelCol > 0 && labelCol < 25) {
      this.setState({ labelCol, wrapperCol: (24 - labelCol) })
    }
    this.getOption()
  }

  async getOption() {

    let arr = this.props.option
    for (let i = 0; i < arr.length; i++) {
      let item = arr[i]
      if (item.hasOwnProperty('api') && item.api !== '') {
        let api = item.api
        await api({ ...item.params }).then(res => {
          if (res.code === 0) {
            if (item.options) {
              item.options = [...item.options, ...res.data]
            }
            else {
              item.options = res.data
            }
          }
        })
      }
      if (item.hasOwnProperty('initialValues')) {
        if (item.type === 'NumRange') {
          this.onSetDefault({
            [item.minKey]: item.initialValues.minKey,
            [item.maxKey]: item.initialValues.maxKey
          })
        } else {
          this.onSetDefault({
            [item.field]: item.initialValues
          })
        }
      }
    }
    this.setState({
      formOption: arr
    })
  }

  onSearch() {
    let values = this.getValues()
    console.log(values);
    this.props.onGetValues(values)
  }

  onReset() {
    this.formRef.resetFields()
    let values = this.getValues()
    this.props.onReset(values)
  }

  onSetDefault(values) {
    this.formRef.setFieldsValue({
      ...values
    });
    return this.getValues()
  }

  getValues() {
    const values = this.formRef.getFieldsValue()
    _.forIn(values, (v, k) => {
      if (v === undefined || v === '' || v === null) {
        delete (values[k])
      }
    })
    return values
  }

  createItem = (item) => {
    let dom
    switch (item.type) {
      case 'NumRange':
        dom = <div style={{ lineHeight: "32px" }}>
          <Form.Item
            name={item.minKey}
            style={{
              display: 'inline-block',
              width: 'calc(50% - 19px)',
              margin: '0 16px 0 0',
            }}
          >
            <InputNumber key={item.field + "NumRangeMin"} {...item.otherConfig}
              onBlur={(e) => this.numRangeChange(e, 'min', item.minKey, item.maxKey)}
              prefix={item.prefix} addonAfter={item.suffix}
              placeholder={item.otherConfig.minPlaceholder??item.placeholder} />
          </Form.Item>
          <span className="ant-form-text">-</span>
          <Form.Item
            name={item.maxKey}
            style={{
              display: 'inline-block',
              width: 'calc(50% - 20px)',
              margin: '0 0 0 8px',
            }}
          >
            <InputNumber key={item.field + "NumRangeMax"} {...item.otherConfig}
              onBlur={(e) => this.numRangeChange(e, 'max', item.minKey, item.maxKey)}
              prefix={item.prefix} addonAfter={item.suffix}
              placeholder={item.otherConfig.maxPlaceholder??item.placeholder} />
          </Form.Item>
        </div>
        break;
      case 'Input':
        dom =
          <Input key={item.field + "-Input"} allowClear placeholder={item.placeholder} {...item.otherConfig}
                onPressEnter={() => this.onSearch()}
                prefix={item.prefix} suffix={item.suffix} maxLength={item.maxLength || null}
          />
        break;
      case 'TreeSelectRegion':
        dom = <TreeSelect
          key={item.field + "-TreeSelectRegion"}
          style={{ width: 300 }}
          treeData={treeData}
          placeholder={item.placeholder}
        />
      case 'InputNumber':
        dom =
          // <span className={item.suffix ? 'inputNumber-suffix' : ''}>
          <InputNumber style={{ width: '100%' }} key={item.field + "InputNumber"} stringMode={item.stringMode ?? false} {...item.otherConfig}
            prefix={item.prefix} addonAfter={item.suffix}
            placeholder={item.placeholder} ></InputNumber>
        {/*  {item.suffix && <i className='suffix'>{item.suffix}</i>}*/ }
        {/*</span>*/ }
        break;
      case 'Select':
        dom = (
          <Select allowClear key={item.field + "Select"} placeholder={item.placeholder} defaultValue={item.defaultValue} mode={item.mode} {...item.otherConfig}>
            {
              item.hasOwnProperty('options') ? item.options.map(option => <Option
                key={option[item.value] || option['value']}
                value={option[item.value] || option['value']}>{option[item.txt] || option['label']}</Option>) : null
            }
          </Select>
        )
        break;
      case 'RangePicker':
        dom = <RangePicker style={{ width: "100%" }} showTime={item.showTime} key={item.field + "RangePicker"}
          allowClear disabledDate={item.disabledDate} picker={item.picker || 'date'}  {...item.otherConfig}/>
        break;
      case 'DatePicker':
        dom = <DatePicker style={{ width: "100%" }} key={item.field + "DatePicker"} allowClear picker={item.picker || 'date'} {...item.otherConfig} placeholder={item.placeholder}/>
        break;
      case 'InputGroupSSelect':
        dom = (
          <Input.Group compact>
            <Form.Item
              name={[item.field, 'Select']}
              noStyle
            >
              <Select
                placeholder={'请选择'}
                key={item.field + "Select"}
                style={{
                  width: 110,
                }}
              >
                {
                  item.hasOwnProperty('options') ? item.options.map(option => <Option
                    key={option.value}
                    value={option[item.value] || option['value']}>{option[item.txt] || option['label']}</Option>) : null
                }
              </Select>
            </Form.Item>
            <Form.Item
              name={[item.field, 'Input']}
              noStyle
            >
              <Input
                key={item.field + "Input"}
                style={{
                  width: 'calc(100% - 110px)',
                }}
                placeholder={item.placeholder}
                allowClear
              />
            </Form.Item>
          </Input.Group>
        )
        break;
      case 'InputGroupDSelect':
        dom = (
          <Input.Group compact>
            <div style={{ width: "100%" }}>
              <Form.Item
                name={[item.field, 'SelectL']}
                noStyle
              >
                <Select
                  key={item.field + "SelectL"}
                  style={{
                    display: 'inline-block',
                    width: 'calc(50% - 5px)',
                  }}
                  placeholder={item.placeholder}
                >
                  {
                    item.hasOwnProperty('options') && item.options.length > 0 ? item.options[0].map(option =>
                      <Option
                        key={option.value}
                        value={option[item.value] || option['value']}>{option[item.txt] || option['label']}</Option>) : null
                  }
                </Select>
              </Form.Item>
              <Form.Item
                name={[item.field, 'SelectR']}
                noStyle
              >
                <Select
                  key={item.field + "SelectR"}
                  style={{
                    display: 'inline-block',
                    width: 'calc(50% - 5px)',
                    marginLeft: 10
                  }}
                  placeholder={item.placeholder}
                >
                  {
                    item.hasOwnProperty('options') && item.options.length > 1 ? item.options[1].map(option =>
                      <Option
                        key={option.value}
                        value={option[item.value] || option['value']}>{option[item.txt] || option['label']}</Option>) : null
                  }
                </Select>
              </Form.Item>
            </div>
          </Input.Group>
        )
        break;
      case 'Cascader':
        dom = (
          <Cascader
            key={item.field + "Cascader"}
            options={item.option}
            changeOnSelect={item.changeOnSelect}
            placeholder={item.placeholder}
            showSearch={(inputValue, path) => path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)}
            loadData={item.loadData ? item.loadData : false}
          />
        )
        break
      case 'Checkbox':
        dom = <Checkbox key={item.field + "Checkbox"} {...item.otherConfig}>{item.text}</Checkbox>
        break;
      default:
        break;
    }
    return dom
  }

  numRangeChange(e, type, minKey, maxKey) {
    const values = this.formRef.getFieldsValue()
    const min = values[minKey], max = values[maxKey]
    if (min !== null && max !== null) {
      if (min > max) {
        this.formRef.setFieldsValue({
          [maxKey]: min,
          [minKey]: max
        })
      }
    }
  }

  onValuesChange(changedValues, allValues) {
    // console.log(changedValues, allValues);
  }
  disabledRangeTime = (current) => {
    if (current) {
      if (current > moment().endOf('day')) {
        return true
      }
    }
  }
  render() {
    const { formOption, layout, labelCol, wrapperCol } = this.state
    const { children, option, show, inline } = this.props
    return (
      <div className='queryForm'>
        <Form
          labelWrap
          labelCol={{
            span: labelCol,
          }}
          wrapperCol={{
            span: wrapperCol,
          }}
          ref={(ref) => this.formRef = ref}
          // layout={'inline'}
          style={{ width: '100%', marginBottom: 12, display: show ? 'inline' : 'none' }}
          onValuesChange={this.onValuesChange}
          className="ant-advanced-search-form"
        >
          <Row gutter={24} style={{ width: "100%", margin: 0 }}>
            {
              formOption && formOption.map((item, index) => {
                return (
                  <Col xxl={8} xl={8} key={"col-" + index}>
                    <Tooltip title={item.tooltip} key={index}>
                      <Form.Item key={item.field} className={index > 3 ? 'form-col' : ''}
                        name={item.type === 'NumRange' ? undefined : item.field}
                        label={item.label}
                        rules={item.rules}
                        labelCol={item.labelCol}
                        wrapperCol={item.wrapperCol}
                        {...item.itemConfig}
                      >
                        {this.createItem(item)}
                      </Form.Item>
                    </Tooltip>
                  </Col>
                )
              })
            }
            {
              (formOption && formOption.length < 3) || inline ? <Form.Item
                style={{ flex: 1, textAlign: 'right' }}
                wrapperCol={24}
              >
                <Space>
                  {children}
                  <Button type="primary" icon={<SearchOutlined />} shape="default"
                    onClick={() => this.onSearch()}>
                    搜索
                  </Button>
                  <Button htmlType="button" icon={<SyncOutlined />} onClick={() => this.onReset()}>
                    重置
                  </Button>
                </Space>
              </Form.Item> : []
            }
          </Row>
          {
            formOption && formOption.length >= 3 && !inline ? <Row>
              <Col
                span={20}
                style={{
                  textAlign: 'left',
                }}
              >
                <Form.Item className='form-btns'>{children}</Form.Item>
              </Col>
              <Col
                span={4}
                style={{
                  textAlign: 'right',
                }}
              >
                <Form.Item className='form-btns' noStyle>
                  <Space>
                    <Button type="primary" icon={<SearchOutlined />} shape="default"
                      onClick={() => this.onSearch()}>
                      搜索
                    </Button>
                    <Button htmlType="button" icon={<SyncOutlined />} onClick={() => this.onReset()}>
                      重置
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row> : []
          }
        </Form>
      </div>
    );
  }
}
TheQueryForm.propTypes = {
  option: PropTypes.array

}
TheQueryForm.defaultProps = {
  option: []
}
